"use client";

import React, { useState, useEffect, Suspense, useCallback, useMemo } from "react";
import { useRouter, useSearchParams } from "next/navigation";
import { Form, Input, Button, Select, Switch, Card, Space, Row, Col, Breadcrumb, Typography, Modal, Divider, Upload, Skeleton } from "antd";
import { useMessage } from "@/hooks/useMessage";
import type { UploadProps } from "antd";
import { SaveOutlined, ArrowLeftOutlined, PlusOutlined, LoadingOutlined } from "@ant-design/icons";
import type { RcFile } from "antd/es/upload/interface";
import dynamic from "next/dynamic";
import { adminAPI, ossAPI, Category } from "@/lib/api";
import AdminLayout from "@/components/AdminLayout";
import { debounce } from "lodash";

const ArticleEditor = dynamic(() => import("@/components/ArticleEditor"), {
  ssr: false,
  loading: () => <Skeleton active paragraph={{ rows: 8 }} />,
});

const { Option } = Select;
const { Title } = Typography;

function ArticleEditForm() {
  const message = useMessage();
  const router = useRouter();
  const searchParams = useSearchParams();
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [html, setHtml] = useState("");
  const [categories, setCategories] = useState<Category[]>([]);
  const [isCategoryModalVisible, setIsCategoryModalVisible] = useState(false);
  const [newCategoryName, setNewCategoryName] = useState("");
  const [uploading, setUploading] = useState(false);
  const [coverImageUrl, setCoverImageUrl] = useState<string>();
  const [currentUser, setCurrentUser] = useState<{ username?: string; id?: number } | null>(null);

  const articleId = searchParams.get("id");
  const isEdit = !!articleId;

  const loadCategories = useCallback(async () => {
    try {
      const res = await adminAPI.getCategories();
      if (res.success) {
        setCategories(res.data);
      }
    } catch (err) {
      console.error("加载分类失败:", err);
      message.error("加载分类失败");
    }
  }, [message]);

  const loadCurrentUser = useCallback(() => {
    if (typeof window !== "undefined") {
      const userInfoStr = localStorage.getItem("userInfo");
      if (userInfoStr) {
        try {
          const userData = JSON.parse(userInfoStr);
          setCurrentUser({ username: userData.username, id: userData.id });
        } catch (err) {
          console.error("解析用户信息失败:", err);
        }
      }
    }
  }, []);

  const handleAddCategory = useCallback(async () => {
    if (!newCategoryName.trim()) {
      message.error("分类名称不能为空");
      return;
    }
    try {
      const res = await adminAPI.createCategory({ name: newCategoryName });
      if (res.success) {
        message.success("分类添加成功");
        setIsCategoryModalVisible(false);
        setNewCategoryName("");
        loadCategories();
      } else {
        message.error(res.error || "添加失败");
      }
    } catch (err) {
      console.error("添加分类失败:", err);
      message.error("添加分类失败");
    }
  }, [newCategoryName, message, loadCategories]);

  const loadArticleData = useCallback(async (id: string) => {
    setLoading(true);
    try {
      const articleIdNum = Number(id);
      if (isNaN(articleIdNum)) {
        message.error("无效的文章ID");
        return;
      }
      const res = await adminAPI.getArticleById(articleIdNum);
      if (res.success) {
        form.setFieldsValue(res.data);
        setHtml(res.data.content);
        if (res.data.coverImage) {
          setCoverImageUrl(res.data.coverImage);
        }
      } else {
        message.error(res.error || "加载文章失败");
      }
    } catch (err) {
      console.error("加载文章数据失败:", err);
      message.error("加载文章数据失败");
    } finally {
      setLoading(false);
    }
  }, [form, message]);

  useEffect(() => {
    loadCategories();
    loadCurrentUser();
    if (isEdit && articleId) {
      loadArticleData(articleId);
    }
  }, [isEdit, articleId, loadCategories, loadCurrentUser, loadArticleData]);

  // 保存文章的核心逻辑
  const handleSaveCore = useCallback(async (shouldReturn = false) => {
    try {
      const values = await form.validateFields();
      setLoading(true);
      const payload = {
        ...values,
        content: html,
        coverImage: coverImageUrl,
      };

      let res;
      if (isEdit) {
        const articleIdNum = Number(articleId);
        if (isNaN(articleIdNum)) {
          message.error("无效的文章ID");
          return;
        }
        res = await adminAPI.updateArticle(articleIdNum, payload);
      } else {
        res = await adminAPI.createArticle(payload);
      }

      if (res.success) {
        message.success(isEdit ? "文章更新成功" : "文章创建成功");
        if (shouldReturn) {
          router.push("/admin/articles");
        }
      } else {
        message.error(res.error || "操作失败");
      }
    } catch (err) {
      console.error("保存失败:", err);
      message.error("保存失败，请检查表单");
    } finally {
      setLoading(false);
    }
  }, [form, html, coverImageUrl, isEdit, articleId, message, router]);

  // 使用防抖处理的保存函数
  const handleSave = useMemo(
    () => debounce(handleSaveCore, 1000, { leading: true, trailing: false }),
    [handleSaveCore]
  );

  const beforeUpload = (file: RcFile) => {
    const isJpgOrPng = file.type === "image/jpeg" || file.type === "image/png";
    if (!isJpgOrPng) {
      message.error("你只能上传 JPG/PNG 格式的图片!");
    }
    const isLt2M = file.size / 1024 / 1024 < 10;
    if (!isLt2M) {
      message.error("图片大小必须小于 10MB!");
    }
    return isJpgOrPng && isLt2M;
  };

  type CustomRequestOptions = Parameters<Required<UploadProps>["customRequest"]>[0];

  const handleCustomRequest = async (options: CustomRequestOptions) => {
    const { file, onSuccess, onError } = options;
    setUploading(true);
    try {
      const res = await ossAPI.getSign();
      if (!res.success) {
        const error = new Error("获取上传签名失败");
        message.error("获取上传签名失败");
        if (onError) onError(error);
        return;
      }

      const { accessKeyId, policy, signature, dir, host } = res.data;
      const key = `${dir}${Date.now()}-${(file as RcFile).name}`;

      const formData = new FormData();
      formData.append("key", key);
      formData.append("policy", policy);
      formData.append("OSSAccessKeyId", accessKeyId);
      formData.append("success_action_status", "200");
      formData.append("signature", signature);
      formData.append("file", file);

      const uploadRes = await fetch(host, {
        method: "POST",
        body: formData,
      });

      if (uploadRes.ok) {
        const imageUrl = `${host}/${key}`;
        setCoverImageUrl(imageUrl);
        // 不再需要手动设置表单值，因为payload会从state中获取
        message.success("封面上传成功");
        if (onSuccess) {
          onSuccess({ url: imageUrl });
        }
      } else {
        throw new Error("上传失败");
      }
    } catch (err) {
      const error = err as Error;
      console.error("上传图片失败:", error);
      message.error("上传图片失败");
      if (onError) onError(error);
    } finally {
      setUploading(false);
    }
  };

  const uploadButton = (
    <div>
      {uploading ? <LoadingOutlined /> : <PlusOutlined />}
      <div style={{ marginTop: 8 }}>上传</div>
    </div>
  );

  return (
    <AdminLayout>
      <Card>
        <div style={{ marginBottom: 24 }}>
          <Breadcrumb items={[{ title: "文章管理", href: "/admin/articles" }, { title: isEdit ? "编辑文章" : "新建文章" }]} />
        </div>

        <div style={{ marginBottom: 16, display: "flex", justifyContent: "space-between", alignItems: "center" }}>
          <Title level={3} style={{ margin: 0 }}>
            {isEdit ? "编辑文章" : "新建文章"}
          </Title>
          <Space>
            <Button icon={<ArrowLeftOutlined />} onClick={() => router.push("/admin/articles")}>
              返回列表
            </Button>
            <Button icon={<SaveOutlined />} onClick={() => handleSave(false)} loading={loading}>
              {isEdit ? "更新" : "保存"}
            </Button>
            <Button type='primary' icon={<SaveOutlined />} onClick={() => handleSave(true)} loading={loading}>
              {isEdit ? "更新并返回" : "保存并返回"}
            </Button>
          </Space>
        </div>

        <Form form={form} layout='vertical' initialValues={{ 
          status: true, 
          isTop: false, 
          isRecommend: false,
          author: currentUser?.username || ''
        }}>
          <Form.Item name='title' label='文章标题' rules={[{ required: true, message: "请输入文章标题" }]}>
            <Input placeholder='请输入文章标题' size='large' />
          </Form.Item>

          <Form.Item name='summary' label='文章摘要' rules={[{ required: true, message: "请输入文章摘要" }]}>
            <Input.TextArea placeholder='请输入文章摘要，用于列表页显示' rows={3} showCount maxLength={200} />
          </Form.Item>

          <Row gutter={16}>
            <Col span={8}>
              <Form.Item name='author' label='作者' rules={[{ required: true, message: "请输入作者" }]}>
                <Input placeholder='请输入作者' />
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item name='categoryId' label='分类' rules={[{ required: true, message: "请选择分类" }]}>
                <Select
                  placeholder='请选择分类'
                  popupRender={menu => (
                    <>
                      {menu}
                      <Divider style={{ margin: "8px 0" }} />
                      <Button type='text' icon={<PlusOutlined />} onClick={() => setIsCategoryModalVisible(true)}>
                        添加分类
                      </Button>
                    </>
                  )}
                >
                  {categories.map(category => (
                    <Option key={category.id} value={category.id}>
                      {category.name}
                    </Option>
                  ))}
                </Select>
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item label='封面图'>
                <Upload name='cover' listType='picture-card' showUploadList={false} customRequest={handleCustomRequest} beforeUpload={beforeUpload}>
                  {coverImageUrl ? <img src={coverImageUrl} alt='封面' style={{ width: "100%" }} /> : uploadButton}
                </Upload>
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={16}>
            <Col span={8}>
              <Form.Item name='status' label='状态' valuePropName='checked'>
                <Switch checkedChildren='已发布' unCheckedChildren='草稿' />
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item name='isTop' label='置顶' valuePropName='checked'>
                <Switch checkedChildren='置顶' unCheckedChildren='普通' />
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item name='isRecommend' label='推荐' valuePropName='checked'>
                <Switch checkedChildren='推荐' unCheckedChildren='普通' />
              </Form.Item>
            </Col>
          </Row>
          <Form.Item label='文章内容' required>
            <ArticleEditor key={articleId || "create"} value={html} onChange={setHtml} />
          </Form.Item>
        </Form>
      </Card>

      <Modal title='添加新分类' open={isCategoryModalVisible} onOk={handleAddCategory} onCancel={() => setIsCategoryModalVisible(false)}>
        <Input value={newCategoryName} onChange={e => setNewCategoryName(e.target.value)} placeholder='请输入新的分类名称' />
      </Modal>
    </AdminLayout>
  );
}

export default function ArticleEditPage() {
  return (
    <Suspense
      fallback={
        <AdminLayout>
          <Card>
            <Skeleton active />
          </Card>
        </AdminLayout>
      }
    >
      <ArticleEditForm />
    </Suspense>
  );
}
